package com.songlin.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import android.graphics.BitmapFactory;

import com.songlin.bakejianshen.R;
import com.songlin.db.Person;
import com.songlin.utils.BitmapUtils;

import java.util.List;

/**
 * Created by moqikaka on 17/5/13.
 */

public class PersonAdapter extends BaseAdapter implements ListAdapter {
    private List<Person> data;
    private Context ctx;

    private Person users;

    private LinearLayout layout_bj;
//    private LinearLayout layout;

    LayoutInflater vi;
    LayoutInflater vi1;

    private int mCount;
    // 一个Bitmap数组，用于缓存获取的图片
    private Bitmap[] images;

    // 需要布局的listview
    private ListView listView;
    private TextView tvNickName;
    private TextView tvAge;
    private ImageView ivHead;

    public PersonAdapter(Context context, List<Person> data, int count) {
        ctx = context;
        this.data = data;
        this.mCount = count;
        // 初始化缓存
        images = new Bitmap[count];

    }

    // 得到image
    private Bitmap getImage(int position) {
        Log.d("Test", "Position:" + position + ":");
        return images[position];

    }

    // 将图片放入数组
    private void cacheImage(int position, Bitmap bitmap) {
        images[position] = bitmap;
        Log.e("Test", "Position:" + position + ":");
    }

    @Override
    public int getCount() {
        return mCount;
    }

    @Override
    public Object getItem(int arg0) {
        return data.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    @Override
    public int getItemViewType(int arg0) {
        return arg0;
    }

    // 跟新view
    @Override
    public View getView(int postion, View convertView, ViewGroup arg2) {

        View view = null;
        //布局不变，数据变

        //如果缓存为空，我们生成新的布局作为1个item
        if(convertView==null){
//            Log.i("info:", "没有缓存，重新生成"+position);
            LayoutInflater inflater = (LayoutInflater) ctx
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            //因为getView()返回的对象，adapter会自动赋给ListView
            view = inflater.inflate(R.layout.friend_one_list, null);
        }else{
//            Log.i("info:", "有缓存，不需要重新生成"+position);
            view = convertView;
        }


        if (postion < data.size()) {
            users = data.get(postion);
        }

//        layout = new LinearLayout(ctx);
//        vi = (LayoutInflater) ctx
//                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//        vi.inflate(R.layout.friend_one_list, layout, true);
        // 获取每一条view的布局
        layout_bj = (LinearLayout) view.findViewById(R.id.list_friend);
        // 初始化控件
        tvNickName = (TextView) view.findViewById(R.id.list_nickName);
        tvAge = (TextView) view.findViewById(R.id.list_age);
        ivHead = (ImageView) view.findViewById(R.id.list_head);

        // 获取查询值
//        String headUrl = users.getHeadUrl();
        String nickName = users.getName();
        String age = String.valueOf(users.getCardNum());

        tvNickName.setText(nickName);
        tvAge.setText(age);

        ivHead.setImageBitmap(BitmapUtils.getImage(users.getHeadName()));


        // 异步加载图片
//        ImageLoadTask imageLoadTask = new ImageLoadTask();
//        imageLoadTask.execute(headUrl, postion);
//        addListener(layout_bj,users);
        return view;
    }

    @Override
    public boolean hasStableIds() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isEmpty() {
        // TODO Auto-generated method stub
        return true;
    }


    @Override
    public boolean areAllItemsEnabled() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isEnabled(int arg0) {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public int getViewTypeCount() {
        // TODO Auto-generated method stub
        return 1;
    }

    // 短按
    public void addListener(LinearLayout layout,final Person user) {

        layout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        });

        layout.setOnTouchListener(new View.OnTouchListener() {


            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
//					layout_bj.setBackgroundColor(Color.rgb(0, 0, 0));
                        break;
                    default:

                        break;
                }
                return false;
            }
        });
    }

    // handle用于接收图片加载好的信息，并修改头像
    private Handler imageHandle = new Handler() {

        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {

                case 1:
                    int postion = msg.arg1;
                    // 根据位置更新头像
                    updateView(postion);
                    break;

                default:
                    break;
            }

        }

        private void updateView(int postion) {
            // 得到第1个可显示控件的位置
            int visiblePosition = listView.getFirstVisiblePosition();
            // 得到你需要更新item的View
            View view = listView.getChildAt(postion - visiblePosition);
            // 获取view的头像控件
            ImageView headView = (ImageView) view
                    .findViewById(R.id.list_head);

            Bitmap bitmap = getImage(postion);
            // 根据position从缓存获取图片
            if (bitmap != null) {

                headView.setImageBitmap(bitmap);

            }
        }

    };

    // 异步类，实现异步加载头像
    class ImageLoadTask extends AsyncTask<Object, Void, Bitmap> {
        int position;

        @Override
        protected Bitmap doInBackground(Object... params) {
            String url = (String) params[0];
            position = (Integer) params[1];

            Bitmap bitmap = bitmap = BitmapUtils.getHttpBitmap(url);

            return bitmap;
        }
        @Override
        protected void onPostExecute(Bitmap result) {
            if (result == null) {
                return;
            }

            // 放入缓存
            cacheImage(position, result);

            // 发送消息给Handle
            Message msg = Message.obtain();
            msg.what = 1;
            msg.arg1 = position;
            imageHandle.sendMessage(msg);

            // 给Adapter发送消息，数据改变
            // 弃用，因为无法改变数据源而无法更新listview,自己写一个Handle监听view的改变
             notifyDataSetChanged();
        }
    }

    public void setListView(ListView listView) {

        this.listView = listView;

    }
}
